package chap1.util;

import java.util.*;

/**
 * http://lxw1234.com
 * lxw的大数据田地
 * @author lxw1234.com
 * http://lxw1234.com/archives/2015/08/458.htm
 *
 */
public class MapUtil {
//    public  static LinkedHashMap<String,Integer> sortedMapByValue(Map<String ,Integer> map){
//        //map按照value升序排序
//        List<Map.Entry<String, Integer>> mapList =
//                new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
//        mapList.sort(Comparator.comparingInt(Map.Entry::getValue));
//        LinkedHashMap<String,Integer> sortedMapByValue = new LinkedHashMap<String,Integer>();
//        for (Map.Entry<String, Integer> x : mapList) {
//
//            sortedMapByValue.put(x.getKey(), x.getValue());
//        }
//        System.out.println("map after sort by value asc " + sortedMapByValue + " ..");
//        return sortedMapByValue;
//    }

//    public  static LinkedHashMap<Character,Integer> sortedMapByValue(Map<Character ,Integer> map){
//        //map按照value升序排序
////        List<Map.Entry<Character, Integer>> mapList =
////                new ArrayList<>(map.entrySet());
////        mapList.sort(Comparator.comparingInt(Map.Entry::getValue));
////        LinkedHashMap<Character,Integer> sortedMapByValue = new LinkedHashMap<>();
////        for (Map.Entry<Character, Integer> x : mapList) {
////
////            sortedMapByValue.put(x.getKey(), x.getValue());
////        }
////        System.out.println("map after sort by value asc " + sortedMapByValue + " ..");
//        return sortedMapByValue(map);
////        return sortedMapByValue;
//    }

//    public  static LinkedHashMap<Object,Integer> sortedMapByValue(Map<Object ,Integer> map){
//        //map按照value升序排序
//        List<Map.Entry<Object, Integer>> mapList =
//                new ArrayList<>(map.entrySet());
//        mapList.sort(Comparator.comparingInt(Map.Entry::getValue));
//        LinkedHashMap<Object,Integer> sortedMapByValue = new LinkedHashMap<>();
//        for (Map.Entry<Object, Integer> x : mapList) {
//
//            sortedMapByValue.put(x.getKey(), x.getValue());
//        }
//        System.out.println("map after sort by value asc " + sortedMapByValue + " ..");
//        return sortedMapByValue;
//    }

    public  static<T> LinkedHashMap<T,Integer> sortedMapByValue(Map<T ,Integer> map){
        //map按照value升序排序
        List<Map.Entry<T, Integer>> mapList =
                new ArrayList<>(map.entrySet());
        mapList.sort(Comparator.comparingInt(Map.Entry::getValue));
        LinkedHashMap<T,Integer> sortedMapByValue = new LinkedHashMap<>();
        for (Map.Entry<T, Integer> x : mapList) {

            sortedMapByValue.put(x.getKey(), x.getValue());
        }
        System.out.println("map after sort by value asc " + sortedMapByValue + " ..");
        return sortedMapByValue;
    }
}
